package clas.ac.cn.common.utils;

import clas.ac.cn.common.exception.IException;
import clas.ac.cn.common.vo.CommonResponse;
import clas.ac.cn.common.vo.ErrMessage;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class WriteResponseUtils {
    public static void writeResponse(HttpServletResponse response, CommonResponse commonResponse, HttpStatus httpStatus) throws Exception {
        if (commonResponse == null || response == null) {
            log.error("WriteResponseUtils=》writeResponse+response/commonResponse为空");
            throw new IException(ErrMessage.ACCIDENT_ERROR);
        }
        if (httpStatus != null) {
            response.setStatus(httpStatus.value());
        }
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(commonResponse));
        writer.close();

    }
}
